<?php

namespace App\Kuafu\Coupon\Model;

use App\Kuafu\Activity\Model\ActivityCouponMappingModel;
use App\Kuafu\Base\Model\Traits\KfSoftDeletes;
use App\Kuafu\Base\Model\BaseModel;
use App\Kuafu\Base\Util\DateTimeUtil;
use App\Kuafu\Coupon\Enum\CouponEnum;

class CouponModel extends BaseModel
{
    use KfSoftDeletes;

    protected $connection = 'mysql';
    protected $table      = 'coupons';
    protected $primaryKey = 'id';
    protected $fillable   = [];
    protected $appends    = [
        'type_text',
        'status_text',
        'discount_text',
        'useTimeType_text',
        'unableDate_text',
        'unableTime_text',
        'startAt_text',
        'endAt_text'
    ];
//    protected $dates = [
//        'startAt',
//        'endAt'
//    ];
    protected $hidden = [
        'updatedAt',
        'isDeleted'
    ];

    public function activityCouponMappings()
    {
        return $this->hasMany(ActivityCouponMappingModel::class, 'couponId', 'id');
    }

    public static function getDataPage($startAt, $name, $type, $channel, $status, $pageSize, $pageNum, $source = '')
    {
        return self::query()
                   ->when($name, function ($query) use ($name) {
                       $query->where('name', 'like', "%{$name}%");
                   })
                   ->when(strlen($type) > 0, function ($query) use ($type) {
                       $query->whereIn('type', explode(",", $type));
                   })
                   ->when(strlen($channel) > 0, function ($query) use ($channel) {
                       $query->whereIn("availableSource", explode(",", $channel));
//                       if ($channel > 0) {
//                           $query->where('availableSource', $channel);
//                       }
                   })
                   ->when(strlen($status), function ($query) use ($status) {
                       $query->where('status', '=', $status);
                   })
//            ->when($startAt, function ($query) use ($startAt) {
//                $query->where('endAt', '>', strtotime($startAt))->orWhere(
//                    'useTimeType', CouponEnum::TIME_TYPE_RELATIVE);
//            })
                   ->when(strlen($source), function ($query) use ($source) {
                switch ($source) {
                    case 'couponPackage':
                        $query->where('costPrice', '=', 0);
                        break;
                }
            })
                   ->orderByDesc('id')
                   ->paginate($pageSize, ['*'], 'pageNum', $pageNum);
    }

    public static function getDataById(int $id)
    {
        return self::query()->where('id', $id)->first();
    }

    public static function addData(array $data)
    {
        return self::query()->create($data);
    }

    public static function setData(int $id, array $data): int
    {
        $query = self::query()->where('id', $id)->first();
        if (!$query) {
            return 0;
        }

        foreach ($data as $k => $v) {
            $query->$k = $v;
        }

        return $query->save();
    }

    public static function setStatus(int $id, int $status): int
    {
        return self::query()->where('id', $id)->update(['status' => $status]);
    }

    public static function delData(int $id): int
    {
        return self::query()->where('id', $id)->update(['isDeleted' => 1]);
    }

    /**
     * 优惠券类型处理
     * @return string
     */
    public function getTypeTextAttribute(): string
    {
        return CouponEnum::COUPONTYPE[$this->type] ?? '';
    }

    /**
     * 优惠券状态处理
     * @return string
     */
    public function getStatusTextAttribute(): string
    {
        return CouponEnum::COUPONSTATUS[$this->status] ?? '';
    }

    /**
     * 优惠力度
     * @return string
     */
    public function getDiscountTextAttribute(): string
    {
        return CouponEnum::ODDERSTRENGTH[$this->discount] ?? '';
    }

    /**
     * 优惠券使用有效期
     */
    public function getUseTimeTypeTextAttribute(): string
    {
        return CouponEnum::COUPONUSETIME[$this->useTimeType] ?? '';
    }

    /**
     * 不可用日期
     * @return mixed|string
     */
    public function getUnableDateTextAttribute()
    {
        if ($this->unableDate) {
            if (strlen($this->unableDate) == 1) {
                return CouponEnum::UNABLE_DATA[(int)$this->unableDate];
            } else {
                $unabledate = '';
                $unable     = explode(',', $this->unableDate);
                foreach ($unable as $item) {
                    $unabledate .= CouponEnum::UNABLE_DATA[(int)$item] . ',';
                }
                return rtrim($unabledate, ',');
            }
        } else {
            return $this->unableDate;
        }
    }

    /**
     * 不可用时间
     * @return mixed
     */
    public function getUnableTimeTextAttribute()
    {
        if (!empty(json_decode($this->unableTime))) {
            $unableTime = json_decode($this->unableTime, true);
            $connection = '';
            foreach ($unableTime as &$item) {
                $connection .= DateTimeUtil::secondsToClock($item['startAt']) . '-' . DateTimeUtil::secondsToClock($item['endAt']) . ',';
            }
            return rtrim($connection, ',');
        } else {
            return '';
        }
    }

    /**
     * 固定时间判断
     * @return false|string
     */
    public function getStartAtTextAttribute()
    {
        if ($this->useTimeType == CouponEnum::TIME_TYPE_ABSOLUTE) {
            return date('Y-m-d H:i:s', $this->startAt);
        }
        return '';
    }

    public function getEndAtTextAttribute()
    {
        if ($this->useTimeType == CouponEnum::TIME_TYPE_ABSOLUTE) {
            return date('Y-m-d H:i:s', $this->endAt);
        }
        return '';
    }

    /**
     * 券内容
     *
     * @param $type
     * @param $discount
     * @param $useCondition
     * @return string
     */
    public static function getCouponDescription($type, $discount, $useCondition)
    {
        switch ($type) {
            case CouponEnum::COUPON_TYPE_VOUCHERS:
                return $useCondition > 0 ? sprintf('每满%d减%d', $useCondition / 100, $discount / 100) : sprintf('无门槛%d',
                    $discount / 100);
                break;
            case CouponEnum::COUPON_TYPE_DISCOUNT:
                return $useCondition > 0 ? sprintf('满%s打%s折', $useCondition / 100, $discount) : sprintf('折扣券 %s 折',
                    $discount);
                break;
            case CouponEnum::COUPON_TYPE_EXCHANGE:
                return CouponEnum::COUPONTYPE[CouponEnum::COUPON_TYPE_EXCHANGE];
                break;
            default:
                return '';
                break;
        }
    }

}
